package com.sofa.permission.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sofa.permission.entity.Role;
import com.sofa.permission.entity.UserRole;
import com.sofa.permission.mapper.RoleMapper;
import com.sofa.permission.mapper.UserRoleMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class PermissionServiceImpl {

    private final UserRoleMapper userRoleMapper;
    private final RoleMapper roleMapper;

    private static final int USER_ROLE_ID = 2;
    private static final int ADMIN_ROLE_ID = 3;

    @Transactional
    public void bindDefaultRole(Long userId) {
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(USER_ROLE_ID); // Default to "user"
        userRoleMapper.insert(userRole);
    }

    public String getUserRoleCode(Long userId) {
        UserRole userRole = userRoleMapper.selectOne(new QueryWrapper<UserRole>().eq("user_id", userId));
        if (userRole == null) {
            return null;
        }
        Role role = roleMapper.selectById(userRole.getRoleId());
        return role != null ? role.getRoleCode() : null;
    }

    @Transactional
    public void upgradeToAdmin(Long userId) {
        updateUserRole(userId, ADMIN_ROLE_ID);
    }

    @Transactional
    public void downgradeToUser(Long userId) {
        updateUserRole(userId, USER_ROLE_ID);
    }

    private void updateUserRole(Long userId, Integer roleId) {
        UserRole userRole = new UserRole();
        userRole.setRoleId(roleId);
        userRoleMapper.update(userRole, new QueryWrapper<UserRole>().eq("user_id", userId));
    }
} 